package com.elink.enginerring.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elink.enginerring.co.BaseCo;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.common.Pagination;
import com.elink.enginerring.dao.CollectionMapper;
import com.elink.enginerring.dao.ThesisMapper;
import com.elink.enginerring.domain.Collection;
import com.elink.enginerring.domain.Thesis;
import com.elink.enginerring.service.CollectionService;
import com.elink.enginerring.util.JSONUtil;

@Service
public class CollectionServiceImpl implements CollectionService {
	@Autowired
	private CollectionMapper collectionMapper;
	@Autowired
	private ThesisMapper thesisMapper;	
	
	@Override
	public Map<String, Object> updateCollect(String userId, String thesisId) {
		Thesis thesis= thesisMapper.selectByPrimaryKey(thesisId);
		if(thesis != null ){
			int count = collectionMapper.select(userId,thesisId);
			if(count == 0 ){ //表示没有收藏过
				Collection c = new Collection();
				c.setUserId(userId);
				c.setThesisId(thesisId);
				c.setCollectionTime(new Date());
				collectionMapper.insertSelective(c);
				//论文的收藏数加一
				thesis.setCollectionCount(thesis.getCollectionCount()+1);
				thesisMapper.updateByPrimaryKeySelective(thesis);
				
				return JSONUtil.getJSON(ErrorType.COLLECTION_SUCCESS);
			}else{
				collectionMapper.delete(userId,thesisId);
				//论文的收藏数减1
				thesis.setCollectionCount(thesis.getCollectionCount()-1);
				thesisMapper.updateByPrimaryKeySelective(thesis);
				
				return JSONUtil.getJSON(ErrorType.CANCEL_COLLECTION);
			}
			
		}else{
			return JSONUtil.getJSON(ErrorType.FILE_COMMENT_ERROR);
		}
	}

	@Override
	public Map<String, Object> getMyCollect(BaseCo co, String userId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", thesisMapper.getMyCollect(co, userId));
		map.put("Pagination",new Pagination(co, thesisMapper.selectCountMyCollect(userId)));
		
		return JSONUtil.getJSON(ErrorType.SUCCESS, map);
	}
}
